<template>
  <div :class="{'app-item':true,'active':dropdownVisible}" @click="onClick">
    <div v-if="showSetting" class="app-item-setting">
      <a-dropdown
        :trigger="['click']"
        :overlayStyle="{'z-index':10}"
        @visibleChange="onDropdownVisibleChange">
        <a-icon type="setting" @click.stop="e => e.preventDefault()"/>
        <a-menu slot="overlay" @click="onSettingMenuClick">
          <a-menu-item key="edit-item">编辑应用</a-menu-item>
          <a-menu-item key="change-icon">更改图标</a-menu-item>
          <a-menu-divider/>
          <a-menu-item key="move-group">移动分组</a-menu-item>
          <a-menu-divider/>
          <a-menu-item key="delete"><span style="color: red;">删除应用</span></a-menu-item>
        </a-menu>
      </a-dropdown>
    </div>
    <low-app-icon-choose
      ref="iconChoose"
      :value="model"
      trigger="semi-auto"
      @change="onIconChooseChange"
      @visibleChange="onIconChooseVisibleChange">
      <low-app-icon :type="model.iconType" :backColor="model.iconBackColor"/>
    </low-app-icon-choose>
    <div class="app-item-name">{{model.appName}}</div>
  </div>
</template>

<script>
import LowAppIcon from './LowAppIcon'
import LowAppIconChoose from './LowAppIconChoose'
import { deleteAction, putAction } from '@api/manage'
import {LOW_APP_DEV_MODE} from '../constant/LowAppConst'

export default {
  name: 'LowAppListItem',
  components: {LowAppIconChoose, LowAppIcon},
  props: {
    item: Object,
    showSetting: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      model: {},
      // 图标信息备份，用于判断图标是否被更改
      iconInfoBackup: {},
      // setting菜单是否显示
      dropdownVisible: false,
      url: {
        edit: '/online/lowApp/edit',
        delete: '/online/lowApp/delete'
      }
    }
  },
  watch: {
    item: {
      deep: true,
      immediate: true,
      handler() {
        this.model = Object.assign({}, this.item)
      }
    },
  },
  methods: {
    onClick(event) {
      // console.log(event)
      this.$emit('click', event)
    },

    onIconChooseChange(value) {
      this.model.iconType = value.iconType
      this.model.iconBackColor = value.iconBackColor
    },
    // 点击setting菜单项
    onSettingMenuClick(e) {
      if (e.key === 'edit-item') {
        this.emitMenuClick(e)
      } else if (e.key === 'change-icon') {
        this.$refs.iconChoose.show()
      } else if (e.key === 'move-group') {
        this.emitMenuClick(e)
      } else if (e.key === 'delete') {
        this.deleteApp()
      }
      this.dropdownVisible = false
    },
    emitMenuClick(e) {
      this.$emit('menu-click', e)
    },
    onDropdownVisibleChange(visble) {
      this.dropdownVisible = visble
    },

    // 在iconChoose面板关闭时，判断是否选择
    onIconChooseVisibleChange(visible) {
      // 在
      if (visible) {
        this.iconInfoBackup = {
          iconType: this.model.iconType,
          iconBackColor: this.model.iconBackColor
        }
      } else {
        // 判断是否有更改，有更改就update
        if (this.iconInfoBackup.iconType !== this.model.iconType
          || this.iconInfoBackup.iconBackColor !== this.model.iconBackColor) {
          this.updateIconInfo()
        }
      }
    },
    appRename() {
      this.$JPrompt({
        title: '更改名称',
        defaultValue: this.model.appName,
        placeholder: '请输入应用名称',
        rule: [{required: true, message: '应用名称不能为空！'}],
        onOkAsync: (event) => {
          event.target.showLoading()
          this.updateApp({
            appName: event.value
          }).then((res) => {
            if (res.success) {
              // this.$message.success(res.message)
              event.target.forceClose()
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => event.target.hideLoading())
        }
      })
    },
    /**更新图标信息*/
    updateIconInfo() {
      this.updateApp({
        iconType: this.model.iconType,
        iconBackColor: this.model.iconBackColor
      }).then(res => {
        // 更新失败，还原图标
        if (!res.success) {
          this.$message.warning('更改图标失败')
          this.model = Object.assign({}, this.item)
          console.warn('更改图标失败：', res)
        }
      })
    },
    // 更新app
    updateApp(formData) {
      return putAction(this.url.edit, {
        ...formData,
        id: this.model.id
      }).then(res => {
        if (res.success) {
          // 无需刷新的重新加载
          try {
            Object.keys(formData).forEach((key) => {
              this.$set(this.item, key, formData[key])
            })
          } catch (e) {
            console.error(e)
          }
        }
        return res
      })
    },
    // 删除app
    deleteApp() {
      this.$JPrompt({
        title: `您确定要删除 “${this.model.appName}” 吗？`,
        content: `该应用相关的所有数据都会一并删除，且不可恢复！<br>如确定删除，请在输入框内输入应用名称：`,
        defaultValue: '',
        placeholder: '请输入应用名称',
        rule: [
          {required: true, message: '应用名称不能为空！'},
          {
            validator: (rule, value, callback) => {
              if (value !== this.model.appName) {
                callback(new Error('请输入正确的应用名称'))
              } else {
                callback()
              }
            }
          },
        ],
        onOkAsync: (event) => {
          event.target.showLoading()
          deleteAction(this.url.delete, {
            id: this.model.id
          }).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.$emit('deleted')
              event.target.forceClose()
              // 应用删除成功，删除缓存
              this.$ls.remove(LOW_APP_DEV_MODE + this.model.id)
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => event.target.hideLoading())
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>

.app-item {
  width: 190px;
  height: 140px;
  border: 1px solid transparent;
  cursor: pointer;
  border-radius: 4px;
  padding: 20px 20px 0;
  display: inline-block;
  vertical-align: top;
  margin: 0 8px;
  position: relative;

  .app-item-icon {
    margin: 10px auto;
  }

  .app-item-name {
    color: #1f2e3d;
    font-size: 16px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    text-align: center;
  }

  .app-item-setting {
    display: none;
    position: absolute;
    top: 4px;
    right: 6px;

  }

  &:hover,
  &.active {
    background-color: #f8f8f8;

    .app-item-setting {
      display: block;
    }
  }
}
</style>